<template>
  <div class="set-word">
    <div class="set-word-header">
      <div class="set-word-header-background">
      </div>
      <!-- <Time :timestamp="this.gameInfo.end_date"
      :image="img"></Time> -->
    </div>
    <div class="functional-area">
      <p class="functional-area-text">集齐以下8个文字即可获得蛋糕一个</p>
      <div class="functional-area-word">
        <ul class="word-one">
          <li v-for="(item, index) of words" :key="item.id" @click="shareIt(item.count, item.word_id)" :class="{ active: index === isactive}">
            <div class="have" >
              <img :src="item.image">
              <span class="sub-script" v-show="item.count">{{item.count}}</span>
            </div>
          </li>
        </ul>
        <span class="table"></span>
        <ul class="word-two">
          <li v-for="(item, index) of words_1" :key="item.id" @click="shareIt(item.count, item.word_id)" :class="{ active: index === isactive1}">
            <div class="have">
              <img :src="item.image">
              <span class="sub-script" v-show="item.count">{{item.count}}</span>
            </div>
          </li>
        </ul>
        <span class="table"></span>
      </div>
      <div class="word-collection-function">
        <div class="word-collection-function-start" @click="start" v-if="starts">
          <p class="word-collection-function-start-text">我要集字</p>
          <p class="word-collection-function-start-frequency">(剩余{{this.word_count}}次)</p>
        </div>
        <div class="word-collection-function-view" @click="view" v-else>
          <p class="word-collection-function-view-text">查看奖励</p>
        </div>
        <div class="interactive">
          <div class="gift-word" @click="giftWord">赠字给好友</div>
          <div class="help" @click="help">求助好友抽字</div>
        </div>
        <div class="attention" @click="openAttention">
          点击关注，马上获得2次抽卡机会
        </div>
      </div>
    </div>
    <div class="winning-list-warpe" v-if="winningLists">
      <winning-list :list="winningLists"></winning-list>
    </div>
    <div class="power-list-warpe" v-if="helpers">
      <power-list :helper="helpers"></power-list>
    </div>
    <div class="rule-warpe">
      <rule @openAttentionShow="openAttention"></rule>
    </div>
    <div class="prize-warpe">
      <prize></prize>
    </div>
    <popup :show="attentionShow" @shutDown="shutDown" v-if="attentionShow"></popup>
    <receive-prize  @closeReceivePrize="closeReceivePrize" v-if="receiveShow"></receive-prize>
    <div class="popup" v-show="guidePictureShow" @click="closeGuidePicture">
      <!-- <yd-popup v-model="attentionShow" position="center"  masker-opacity=".7">
        <div class="guide-picture">
          <img src="../../assets/img/shart.png" alt="">
        </div>
      </yd-popup> -->
      <div class="guide-picture">
        <img src="../../assets/img/shart.png" class="guide-picture-image">
      </div>
      <!-- <div class="shut-down">
        <img src="../../assets/img/shut-down.png" class="shut-down-image">
      </div> -->
    </div>
  
    <div class="popups" v-show="popupShow" @touchmove="touchMove($event)">
      <div class="rotate">
        <img src="../../assets/img/zhuan.png" class="rotate-image">
      </div>
      <div class="information">
        <div class="middle">
          <p class="title">抽中</p>
          <div class="pumping">
            <img :src="this.dark_image" class="pumping-image">
          </div>
        </div>
        <div class="buttons">
          <div class="buttons-back" @click="closePopup">知道啦</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Time from "../../components/Time"
import PowerList from "../../components/PowerList"
import Rule from "../../components/Rule"
import Prize from "../../components/Prize"
import Popup from "../../components/Popup"
import WinningList from '../../components/WinningList'
import ReceivePrize from '../../components/ReceivePrize'
import $fly from "flyio"
import api from "../../assets/js/api.js"
// import { Alert } from 'vue-ydui/dist/lib.rem/dialog'
import wx from "weixin-js-sdk"
import { Toast, Dialog, Step, Steps } from "vant"
export default {
  name: "WordPage",
  components: {
    Time,
    PowerList,
    Rule,
    Prize,
    Popup,
    WinningList,
    ReceivePrize,
    Toast,
    Dialog,
    Step,
    Steps
  },
  data() {
    return {
      attentionShow: false, //关注公众号弹窗的显示
      receiveShow: false, //领奖页面的显示
      guidePictureShow: false, // 邀请好友抽字页面的显示
      words: {}, //当前用户拥有的文字集合
      words_1: {}, //布局中第二排的文字集合
      gameInfo: '',
      helpers: '', //助力榜信息
      word_count: "", //抽字次数
      img: "",
      giftReminderShow: false,
      drawnWord: "", //抽到的字
      isactive: 0, //判断循环出来的文字当前在那个元素，用于动态添加class
      isactive1: 5, //同上，用户文字第二排
      interval: "", //标准速度定时器
      interval_1: "", //快速定时器
      interval_2: "", //停止定时器,
      popupShow: false, //抽字弹窗变量,
      dark_image: "", //弹窗显示的字
      canClick: true, //开始集字按钮是否可以点击
      complete_time: 0, //用户集齐所有字的时间，大于0表示已经集齐
      starts: true, //集字按钮还是查看按钮显示条件
      winningLists: '', //用户集字榜，传给子组件WinningList
      error: '', //网络请求错误信息
      name: null //当前用户微信名
    }
  },
  beforeRouteEnter(to, from, next) {
    if (!localStorage.getItem("access_token")) {
      localStorage.setItem("wordPage", "wordPages")
      next("/")
    } else {
      next()
    }
  },
  async mounted () {
    this.rank()
    await this.authRequests()
    await this.openOrClose()
    await this.jsSdk()
    this.$nextTick( () => {
      this.bindClass()
    })
  },
  methods: {
    openAttention() {
      this.attentionShow = true
    },
    shutDown(e) {
      this.word_count = e
      this.attentionShow = false
    },
    openOrClose () {
      if ( this.complete_time > 0 ) {
        this.starts = false
      }
    },
    async authRequests() {
      await api.authRequest("user?include=words,helpers,game")
            .then(res => {
              this.unique_no = res.data.unique_no
              this.gameInfo = res.data.game
              this.helpers = res.data.helpers.data
              this.words = res.data.words.data
              this.word_count = res.data.word_count
              this.words_1 = this.splices(this.words)
              this.img = res.data.game.image
              this.complete_time = res.data.complete_time
              this.name = res.data.name
            })
            .catch(err => {
              console.log(err)
            })
    },
    rank () {
      api.authRequest("game/rank")
      .then( (res) => {
        if (res.status === 200) {
          this.winningLists = res.data
        }
      })
      .catch( (err) => {
        console.log(err)
      })
    },
    jsSdk () { //获取微信sdk
      $fly.get(`${api.host}/weixin/jssdk`, {
        url: location.href
      })
      .then( (res) => {
        if (res.status === 200) {
          const unique = this.unique_no //创建用户唯一标识，用于微信自定义分享，因为wx自定义分享重无法获取this.unique_no
          wx.config({
            debug: true,
            appId: res.data.appId,
            nonceStr: res.data.nonceStr,
            timestamp: res.data.timestamp,
            signature: res.data.signature,
            jsApiList: res.data.jsApiList
          })
          wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
            wx.updateAppMessageShareData({ 
              title: '集字赢好礼', // 分享标题
              desc: '我正在参加集字抢好礼活动，请求支援！', // 分享描述
              link: `http://word.xmfinger.com/PowerListPage?unique=${unique}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: 'http://word.xmfinger.com/icon.png',
              success: function () {
                // 设置成功
              }
            })
            wx.updateTimelineShareData({ 
              title: '我正在参加集字抢好礼活动，请求支援！', // 分享标题
              link: `http://word.xmfinger.com/PowerListPage?unique=${unique}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: 'http://word.xmfinger.com/icon.png', // 分享图标
              success: function () {
                // 设置成功
              }
            })
          })
        }
      })
      .catch( (err) => {
        console.log(err)
      })
    },
    start() {
      if ( this.word_count > 0 ) {
        if ( this.canClick ) {
          clearInterval(this.interval)
          this.fastBindClass()
          api
            .authRequest({
              url: "words?include=user.words",
              method: "post"
            })
            .then(res => {
              if (res.status === 200) {
                this.dark_image = res.data.dark_image
                this.drawnWord = res.data.name
                this.word_count = res.data.user.word_count
                this.complete_time = res.data.user.complete_time
                setTimeout( () => {
                  this.words = res.data.user.words.data
                  this.words_1 = this.splices(this.words)
                }, 6000)
              }
            })
            .catch(err => {
              console.log(err)
              // if (err.status === 400 || err.status === 422) { //根据 后端返回的错误状态码，提示用户
              //   Dialog.alert({
              //     message: err.response.data.message
              //   })
              // }
            })
          setTimeout(() => {
            this.slowDownClass()
          }, 2000)
        }
      } else {
        Dialog.alert({
          message: '您的抽字次数今日已用完，请明日再来！'
        })
      }
      
    },
    splices(words) {
      let words_1 = words.splice(4)
      return words_1
    },
    shareIt(i, e) {
      if ( this.complete_time > 0 ) {
        if ( i >= 2 ) {
          Dialog.confirm({
            title: "赠字给好友",
            message: "确定将该字赠送给好友？"
          })
            .then((res) => {
              api.authRequest({
                  url: "words/send",
                  data: { word_id: e },
                  method: "post"
                })
                .then(res => {
                  if (res.status === 200) {
                    localStorage.setItem("giftPage", "giftPage")
                    // let isIos = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) 判断手机操作系统
                    this.$router.push({
                      path: "/GiftPage",
                      query: { names: this.name, code: res.data.code }
                    })
                  }
                })
                .catch(err => {
                  if (err.status === 422) {
                    Dialog.alert({
                      message: err.response.data.message
                    })
                  }
                  if (err.status === 404) {
                    Dialog.alert({
                      message: err.response.data.message
                    })
                  }
                  console.log(err)
                })
            })
            .catch(err => {
              console.log(err)
            })
          } else {
              Dialog.alert({
                message: '您已经集齐所有字，但您现在要赠送给好友的字，你有且只有一个，赠送给好友，您将失去兑奖资格！'
              }).then(() => {
                // on close
              });
          }
      } else {
          Dialog.confirm({
            title: "赠字给好友",
            message: "确定将该字赠送给好友？"
          })
            .then((res) => {
              api.authRequest({
                  url: "words/send",
                  data: { word_id: e },
                  method: "post"
                })
                .then(res => {
                  if (res.status === 200) {
                    localStorage.setItem("giftPage", "giftPage")
                    this.$router.push({
                      path: "/GiftPage",
                      query: { names: this.name, code: res.data.code }
                    })
                  }
                })
                .catch(err => {
                  if (err.status === 422) {
                    Dialog.alert({
                      message: err.response.data.message
                    })
                  }
                  if (err.status === 404) {
                    Dialog.alert({
                      message: err.response.data.message
                    })
                  }
                  console.log(err)
                })
            })
            .catch(err => {
              console.log(err)
            })
      }
    },
    help() {
      this.guidePictureShow = true
      
      // localStorage.setItem("helpingFriends", "helpingFriends") //存一个数据用来判断，进入分享求组页面该跳转的页面
      // this.$router.push({
      //   path: "/HelpingFriends",
      //   query: { unique_no: this.unique_no }
      // }) //跳转到求助页面，带查询参数
    },
    closeGuidePicture () { //关闭求助好友功能的引导用户关注页面
      this.guidePictureShow = false
    },
    giftWord() {
      Dialog.alert({
        message: `点击您想赠送给好友的字，发送给好友即可！`
      }).then(() => {
        // on close
      })
    },
    closeGiftReminder() {
      this.giftReminderShow = false
    },
    beforeClose(action, done) {
      if (action === "confirm") {
        done()
        this.giftReminderShow = false
      } else {
        done()
      }
    },
    bindClass() { //标准速度改变文字的背景色
      this.interval = setInterval(() => {
        this.isactive++
        if (this.isactive === 4) {
          this.isactive = 4
          this.isactive1 = 4
        }

        if (this.isactive1 <= 4) {
          this.isactive1--
        } else if (this.isactive1 <= -1) {
          this.isactive1 = 5
        }

        if (this.isactive1 === 0) {
          this.isactive = -1
        }
      }, 1000)
    },
    bindClass_1() { //慢速改变字体背景色
      this.interval = setInterval(() => {
        this.isactive++
        if (this.isactive === 4) {
          this.isactive = 4
          this.isactive1 = 4
        }

        if (this.isactive1 <= 4) {
          this.isactive1--
        } else if (this.isactive1 <= -1) {
          this.isactive1 = 5
        }

        if (this.isactive1 === 0) {
          this.isactive = -1
        }
      }, 300)
    },
    fastBindClass() { //快速改变字体背景色
      this.canClick = false
      this.interval_1 = setInterval(() => {
        this.isactive++
        if (this.isactive === 4) {
          this.isactive = 4
          this.isactive1 = 4
        }

        if (this.isactive1 <= 4) {
          this.isactive1--
        } else if (this.isactive1 <= -1) {
          this.isactive1 = 5
        }

        if (this.isactive1 === 0) {
          this.isactive = -1
        }
      }, 100)
    },
    slowDownClass() { //减速函数，并停止改变字体背景颜色，再弹窗
      clearInterval(this.interval_1)
      this.bindClass_1()
      this.interval_2 = setInterval(this.stop, 200)
    },
    stop() { //停止函数，在抽中的字位置停止，并弹窗
      if (this.drawnWord === "感" && this.isactive === 0) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      } else if (this.drawnWord === "恩" && this.isactive === 1) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      } else if (this.drawnWord === "回" && this.isactive === 2) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      } else if (this.drawnWord === "馈" && this.isactive === 3) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      } else if (this.drawnWord === "幸" && this.isactive1 === 0) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      } else if (this.drawnWord === "福" && this.isactive1 === 1) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      } else if (this.drawnWord === "美" && this.isactive1 === 2) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      } else if (this.drawnWord === "味" && this.isactive1 === 3) {
        clearInterval(this.interval)
        clearInterval(this.interval_2)
        setTimeout(() => {
          this.popupShow = true
        }, 1000)
      }
    },
    closePopup() {
      this.canClick = true

      this.popupShow = false

      if ( this.complete_time > 0 ) {
        this.starts = false
        Dialog.alert({
          message: `恭喜您已经集齐所有的字，点击查看奖励的按钮去领取吧！`
        }).then(() => {
          // on close
        })
      }

      this.bindClass()
    },
    view () {
      this.receiveShow = true
    },
    touchMove (e) { //停止触摸滚动
      e.preventDefault() //阻止事件的默认行为
      e.stopPropagation() //阻止冒泡
    },
    closeReceivePrize () {
      this.receiveShow = false
    }
  },
  beforeDestroy() {
    localStorage.removeItem("wordPage")
    clearInterval(this.interval)  //页面销毁摧毁关闭定时器
    clearInterval(this.interval_1)
    clearInterval(this.interval_2)
    setTimeout(localStorage.removeItem("giftPage"), 2000) //1秒后删除这个数据，释放空间
    // setTimeout(localStorage.removeItem('helpingFriends'), 2000)
  }
}
</script>

<style lang="stylus" scoped>
.set-word {
  background: url('../../assets/img/wordpage-background-img.png') no-repeat
  background-size: cover
  height:4135px

  .set-word-header {
    padding-top: 78px

    .set-word-header-background {
      margin: 0 auto 31px
      width: 235px
      height: 44px
      background: url('../../assets/img/wordpage-header.png') no-repeat
      background-size: cover
    }
  }

  .functional-area {
    margin-top: 45px
    margin-bottom: 112px

    .functional-area-text {
      font-size: 30px /* px */
      color: #fff
      text-align: center
    }

    .functional-area-word {
      margin: 10px auto 0
      width: 692px
      transform: perspective(1000)
      -moz-transform: perspective(1000)
      -o-transform: perspective(1000)
      -webkit-transform: perspective(1000)

      .word-one, .word-two {
        display: flex
        justify-content: center
        height: 100px
        perspective: 1000
        -webkit-perspective: 1000
        transform: perspective(1000)
        -moz-transform: perspective(1000)
        -o-transform: perspective(1000)
        -webkit-transform: perspective(1000)
        transform: translate3d(10px, 50px, 80px)

        li {
          position: relative
          width: 147px
          height: 161px
        }

        & .active {
          background-color: #99FFFF
          border-radius: 10%
          border: 1px solid transparent
        }

        .have {
          width: 147px
          height: 161px

          img {
            width: 100%
            height: auto
          }

          .sub-script {
            position: absolute
            top: -10px
            right: 0
            width: 58px
            height: 59px
            background: url('../../assets/img/sub-script.png') no-repeat
            background-size: cover
            display: flex
            align-items: center
            justify-content: center
            padding-right: 8px
            color: #fff
          }
        }
      }

      .table {
        display: inline-block
        width: 692px
        height: 131px
        background: url('../../assets/img/table.png') no-repeat
        background-size: cover
        margin-top: 30px
      }
    }

    .word-collection-function {
      margin-top: 90px

      .word-collection-function-start {
        width: 456px
        height: 138px
        background: url('../../assets/img/wordpage-start.png') no-repeat
        background-size: cover
        margin: 0 auto
        display: flex
        flex-direction: column
        text-align: center
        padding-top: 18px
        color: #fff

        .word-collection-function-start-text {
          font-size: 48px
          margin-bottom: 14px
          letter-spacing: 2px
        }

        .word-collection-function-start-frequency {
          font-size: 30px
          letter-spacing: 2px
        }
      }

      .word-collection-function-view {
        width: 456px
        height: 138px
        background: url('../../assets/img/wordpage-start.png') no-repeat
        background-size: cover
        margin: 0 auto
        display: flex
        justify-content center
        align-items center
        color: #fff
        font-size: 48px
      }

      .interactive {
        margin: 44px auto 0
        width: 624px
        display: flex
        justify-content: space-between

        .gift-word, .help {
          width: 270px
          height: 70px
          background: url('../../assets/img/gift-word.png') no-repeat
          background-size: cover
          color: #ffffff
          font-size: 36px /* px */
          line-height: 73px
          text-align: center
        }
      }

      .attention {
        margin: 39px auto 0
        color: #fff
        font-size: 28px
        border-bottom: 2px solid #fff
        width: 426px
        height: 35px
        line-height: 28px
        text-align: center
      }
    }
  }

  .winning-list-warpe {
    margin-bottom: 120px  
  }
  .power-list-warpe {
    margin-bottom: 120px
  }

  .rule-warpe {
    margin-bottom: 120px
  }
 
  .popup {
    position fixed
    top 0
    left 0
    bottom 0
    right 0
    width 100%
    height 100%
    background-color rgba(0, 0, 0, 0.8)

    .guide-picture {
      width 750px
      height 258px
      position fixed
      top -12px
      left 0
      .guide-picture-image {
        width 100%
        height auto
      }
    }
  }

  .popups {
    width: 100%
    height: 100%
    position: fixed
    top: 0
    left: 0
    background-color: rgba(0, 0, 0, 0.6)

    .rotate {
      width: 900px
      height: 900px
      position: absolute
      top: 130px
      left: 50%
      margin-left: -450px
      animation: rotate 20s infinite linear

      .rotate-image {
        width: 100%
        height: auto
      }
    }

    @keyframes rotate {
      0% {
        transform: rotate(0deg)
      }

      100% {
        transform: rotate(360deg)
      }
    }

    .information {
      width: 530px
      height: 600px
      position: absolute
      top: 50%
      left: 50%
      transform: translate(-50%, -50%)
      background: url('../../assets/img/chouzhongla.png') no-repeat
      background-size: contain
      background-color: #fff

      .middle {
        margin-top: 180px

        .title {
          font-size: 36px
          text-align: center
          color: #707070
        }

        .pumping {
          margin: 30px auto 0
          text-align: center
          width 147px
          height 161px
        }

        .pumping-image {
          width 100%
          height auto
        }
      }

      .buttons {
        margin-top: 35px
        text-align: center

        .buttons-back {
          width: 270px
          height: 70px
          line-height 70px
          color: #fff
          font-size: 32px
          background: url("../../assets/img/gift-word.png") no-repeat
          background-size cover
          margin 0 auto
        }
      }
    }
  }
}
</style>
